'use client'

import { useEffect, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { VmsCourse, VmsCourseSection, VmsCopy } from '@/types/Model'
import { Button } from '@/components/ui/button'
import { ArrowLeft } from 'lucide-react'
import { toast } from '@/hooks/use-toast'
import CourseInfo from './components/CourseInfo'
import SectionManager from './components/SectionManager'

export default function CourseDetailPage() {
  const params = useParams()
  const router = useRouter()
  const courseId = params.id as string
  
  const [course, setCourse] = useState<VmsCourse | null>(null)
  const [sections, setSections] = useState<VmsCourseSection[]>([])
  const [copies, setCopies] = useState<VmsCopy[]>([])
  const [loading, setLoading] = useState(true)

  // 获取课程详情
  const fetchCourse = async () => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/course/${courseId}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        if (response.status === 401) {
          router.push('/login')
          return
        }
        throw new Error('Failed to fetch course')
      }
      
      const data = await response.json()
      setCourse(data)
      setSections(data.sections || [])
    } catch (error) {
      console.error('Error fetching course:', error)
      toast({
        title: '获取课程失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  // 获取文案列表
  const fetchCopies = async () => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch('/api/copy', {  // 问题：缺少 topic_id 参数
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (response.ok) {
        const data = await response.json()
        setCopies(data)
      }
    } catch (error) {
      console.error('Error fetching copies:', error)
    }
  }

  useEffect(() => {
    if (courseId) {
      fetchCourse()
      fetchCopies()
    }
  }, [courseId])

  useEffect(() => {
    if (course) {
      setLoading(false)
    }
  }, [course])

  // 创建小节
  const handleCreateSection = async (sectionData: Partial<VmsCourseSection>) => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/course/${courseId}/sections`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(sectionData)
      })
      
      if (!response.ok) {
        throw new Error('Failed to create section')
      }
      
      const newSection = await response.json()
      setSections(prev => [...prev, newSection])
      toast({
        title: '创建成功',
        description: '课程小节已创建'
      })
    } catch (error) {
      console.error('Error creating section:', error)
      toast({
        title: '创建失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  // 批量从文案创建小节
  const handleCreateFromCopies = async (copyIds: string[]) => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/course/${courseId}/sections`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ copy_ids: copyIds })
      })
      
      if (!response.ok) {
        throw new Error('Failed to create sections from copies')
      }
      
      const newSections = await response.json()
      setSections(prev => [...prev, ...newSections])
      toast({
        title: '创建成功',
        description: `已从文案创建 ${newSections.length} 个小节`
      })
    } catch (error) {
      console.error('Error creating sections from copies:', error)
      toast({
        title: '创建失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  // 删除小节
  const handleDeleteSection = async (sectionId: string) => {
    if (!confirm('确定要删除这个小节吗？此操作不可撤销。')) {
      return
    }

    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/course/${courseId}/sections/${sectionId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        throw new Error('Failed to delete section')
      }
      
      setSections(prev => prev.filter(s => s.id !== sectionId))
      toast({
        title: '删除成功',
        description: '课程小节已删除'
      })
    } catch (error) {
      console.error('Error deleting section:', error)
      toast({
        title: '删除失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  // 添加处理编辑小节的函数
  const handleUpdateSection = async (sectionData: Partial<VmsCourseSection>) => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/course/${courseId}/sections/${sectionData.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(sectionData)
      })
      
      if (!response.ok) {
        throw new Error('Failed to update section')
      }
      
      const updatedSection = await response.json()
      setSections(prev => prev.map(section => 
        section.id === updatedSection.id ? updatedSection : section
      ))
      toast({
        title: '更新成功',
        description: '课程小节已更新'
      })
    } catch (error) {
      console.error('Error updating section:', error)
      toast({
        title: '更新失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  const handleCourseUpdated = (updatedCourse: VmsCourse) => {
    setCourse(updatedCourse)
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-slate-50 to-white flex justify-center items-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-rose-600"></div>
      </div>
    )
  }

  if (!course) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-slate-50 to-white flex justify-center items-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-slate-900 mb-2">课程未找到</h2>
          <p className="text-slate-600 mb-4">请检查课程ID是否正确</p>
          <Button onClick={() => router.push('/courses')}>返回课程列表</Button>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-rose-50/30">
      <div className="container mx-auto py-8 px-4">
        {/* 页面头部 */}
        <div className="mb-8">
          <div className="flex items-center gap-4 mb-6">
            <Button 
              variant="ghost" 
              onClick={() => router.push('/courses')}
              className="flex items-center gap-2 text-slate-600 hover:text-slate-900"
            >
              <ArrowLeft className="h-4 w-4" />
              返回课程列表
            </Button>
          </div>
          
          <CourseInfo 
            course={course} 
            sectionsCount={sections.length}
            onCourseUpdated={handleCourseUpdated}
          />
        </div>

        <SectionManager
          sections={sections}
          copies={copies}
          courseId={courseId}
          onSectionsUpdate={setSections}
          onCreateSection={handleCreateSection}
          onUpdateSection={handleUpdateSection}  // 添加这一行
          onDeleteSection={handleDeleteSection}
          onCreateFromCopies={handleCreateFromCopies}
        />
      </div>
    </div>
  )
}

